import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:common/global/global_blocs.dart';
import 'package:common/global/global_event.dart';
import 'package:common/global/global_route_manager.dart';
import 'package:common/l10n/localizations.dart';
import 'package:common/module/module_registrar.dart';
import 'package:common/common.dart';

import 'module_route_manager.dart';

class ModuleManager {
  static ModuleManager _instance;

  static void init(BuildType buildType) {
    _instance = ModuleManager._(buildType);
  }

  factory ModuleManager() {
    return _instance;
  }

  ModuleManager._(BuildType buildType) {
    _instance = this;
    _buildType = buildType;
    _delegates = [
      AppLocalizations.delegate,
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      GlobalCupertinoLocalizations.delegate,
      DefaultCupertinoLocalizations.delegate
    ];
    GlobalBlocs.add({UserBloc.blocName: UserBloc(UserBlocState(status: UserStatus.Initializing))});
  }

  BuildType get buildType => _buildType;
  BuildType _buildType;

  List<Function(GlobalEvent)> _eventHandlers = [];

  List<LocalizationsDelegate> _delegates;
  List<ModuleRouteManager> _routerManagers;

  List<Function(GlobalEvent)> get eventHandlers => _eventHandlers;

  List<LocalizationsDelegate> get localizationDelegates => _delegates;

  List<ModuleRouteManager> get routerManagers => _routerManagers;

  List<Future> get onStartUpFutures => onStartUpFutures;

  void register(ModuleRegistrar registrar) {
    registrar.setBuildType(buildType);
    if(registrar.localizationsDelegate!=null){
      _delegates.add(registrar.localizationsDelegate);
    }

    Function(GlobalEvent) handler = registrar.eventHandler;

    if (handler != null) {
      _eventHandlers.add(handler);
    }

    if(registrar.routerManager!=null){
      GlobalRouterManager.registerRoutes(registrar.routerManager.routes);
    }


    Map<String, Bloc> blocs = registrar.globalBlocs;
    if (blocs != null) {
      GlobalBlocs.add(blocs);
    }
  }
}
